package org.example.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * @Author: wwy
 * @Date: 2020/11/26 15:40
 */
@Service
public class FileHandleService {
    /**
     * 文件目录
     */
    @Value("${file.filePath}")
    private String filePath;
    /**
     * 保存数据到磁盘
     * @param fileName
     * @param content
     */
    public void saveFile(String fileName,String content){
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
        }
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(new File(file,fileName));
            fileWriter.write(content);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileWriter !=null){
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据文件名称读取文件
     * @param fileName
     * @return
     */
    public String readFile(String fileName){
        String content = "";
        File file = new File(filePath+fileName);
        if(!file.exists()){
            return null;
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString;
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                content += tempString;
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(reader!=null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }
}
